package com.bjpowernode.app;
//锁对象才能调用notifyAll();或者wait();方法
//锁对象的条件
//1——必须是对象
//2——必须synchronized ()修饰
//锁对象的两个方法
//1——notifyAll();通知所有线程，放行Thread.State.BLOCKED线程
//2——wait();让线程进行阻塞（Thread.State.BLOCKED）
public class MyApp6 {
    public Object lock = new Object();
    Runnable r1 = () -> {
        synchronized (lock) {
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":" + i);
//                //锁通知
//                //当前线程如果wait()阻塞【Thread.State.BLOCKED】，则继续通行
                lock.notifyAll();
                try {
                    //锁等待
                    //放锁+当前线程阻塞
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lock.notifyAll();
        }
    };
    Runnable r2 = () -> {
        synchronized (lock) {
            for (int i = 201; i <= 220; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":" + i);
                //锁通知
                lock.notifyAll();
                try {
                    //锁等待
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lock.notifyAll();
        }
    };

    public static void main(String[] args) {
        MyApp6 myApp6 = new MyApp6();
        Thread t1 = new Thread(myApp6.r1, "r1");
        Thread t2 = new Thread(myApp6.r2, "r2");
        t1.start();
        t2.start();
    }

}
